package com.xidian.zhiancloud.service.emergencyManagement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dto.emergencyManagement.EmergencyDrillPlanDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.emergencyManagement.EmergencyDrillPlanQO;
import com.xidian.zhiancloud.vo.emergencyManagement.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

@Service
public class EmergencyDrillPlanService extends ServiceImpl<EmergencyDrillPlanMapper, EmergencyDrillPlan> implements IService<EmergencyDrillPlan> {

    @Autowired
    private EmergencyDrillPlanMapper emergencyDrillPlanMapper;

    @Autowired
    private EmergencyDivisionOfTasksMapper emergencyDivisionOfTasksMapper;

    @Autowired
    private EmergencyPlanManagementMapper emergencyPlanManagementMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean add(EmergencyDrillPlanDTO emergencyDrillPlanDTO) {
        EmergencyDrillPlan emergencyDrillPlan = emergencyDrillPlanDTO.getEmergencyDrillPlan();
        int result = emergencyDrillPlanMapper.insert(emergencyDrillPlan);
        if (result == 0) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        int count = 0;
        emergencyDrillPlan.setStatus(0);
        for(int i=0;i<emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList().size();i++){
            emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList().get(i).setEmergencyDrillId(emergencyDrillPlanDTO.getEmergencyDrillPlan().getId());
            emergencyDivisionOfTasksMapper.insert(emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList().get(i));
            count++;
        }
        if (count != emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList().size()) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        return true;
//        for(EmergencyDivisionOfTasks emergencyDivisionOfTasks: emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList()){
//            emergencyDivisionOfTasks.setEmergencyDrillId(emergencyDrillPlanDTO.getEmergencyDrillPlan().getId());
//            int tmp = emergencyDivisionOfTasksMapper.insert(emergencyDivisionOfTasks);
//            if(tmp==0){
//                throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
//            }
//        }
    }

    public EmergencyDrillPlanDTOVO getById(Long id) {
        EmergencyDrillPlan emergencyDrillPlan = emergencyDrillPlanMapper.selectById(id);
        if(emergencyDrillPlan==null){
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        //修改为mybatis plus的条件查询
        QueryWrapper<EmergencyDivisionOfTasks> emergencyDivisionOfTasksQueryWrapper = new QueryWrapper<EmergencyDivisionOfTasks>();
        emergencyDivisionOfTasksQueryWrapper.eq("emergency_drill_id",id);
        List<EmergencyDivisionOfTasks> emergencyDivisionOfTasksList=emergencyDivisionOfTasksMapper.selectList(emergencyDivisionOfTasksQueryWrapper);

        EmergencyDrillPlanDTOVO res=new EmergencyDrillPlanDTOVO();
        EmergencyDrillPlanVO vo=new EmergencyDrillPlanVO();
        BeanUtils.copyProperties(emergencyDrillPlan,vo);
        EmergencyPlanManagement plan=emergencyPlanManagementMapper.selectById(vo.getNameRId());
        vo.setNameEmerge(plan==null?"该应急预案不存在":plan.getName());
        Organization org = organizationMapper.selectById(vo.getOrganizationId());
        vo.setOrganizationName(org==null?"该部门不存在":org.getName());


        List<EmergencyDivisionOfTasksVO> voList=new LinkedList<>();
        List<String> participantNames=new LinkedList<>();
        for (int i = 0; i < emergencyDivisionOfTasksList.size(); i++) {
            EmergencyDivisionOfTasksVO vos=new EmergencyDivisionOfTasksVO();
            BeanUtils.copyProperties(emergencyDivisionOfTasksList.get(i),vos);
            SysUser userid =sysUserMapper.selectById(vos.getNameId());
            vos.setPersonnelName(userid==null?"该用户不存在":userid.getName());
            voList.add(vos);
            participantNames.add(userid.getName());
        }
        res.setEmergencyDivisionOfTasksVOList(voList);
        vo.setParticipantNames(participantNames.toString());

        res.setEmergencyDrillPlanVO(vo);
        return res;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean deleteByIds(Long[] ids) {
        int res = 0;
        int res2 = 0;
        for(int i=0;i<ids.length;i++){
            //mybatis plus的条件删除
            LambdaQueryWrapper<EmergencyDivisionOfTasks> emergencyDivisionOfTasksLambdaQueryWrapper=Wrappers.<EmergencyDivisionOfTasks>lambdaQuery();
            emergencyDivisionOfTasksLambdaQueryWrapper.eq(EmergencyDivisionOfTasks::getEmergencyDrillId,ids[i]);
            res+=emergencyDivisionOfTasksMapper.delete(emergencyDivisionOfTasksLambdaQueryWrapper);
            res2+=emergencyDrillPlanMapper.deleteById(ids[i]);
//            EmergencyDivisionOfTasksExample emergencyDivisionOfTasksExample = new EmergencyDivisionOfTasksExample();
//            emergencyDivisionOfTasksExample.createCriteria().andEmergencyDrillIdEqualTo(ids[i]);
//            emergencyDivisionOfTasksMapper.deleteByExample(emergencyDivisionOfTasksExample);
        }
        if (res == 0 || res2 == 0) {
            return false;
        }
        return true;
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean patchById(EmergencyDrillPlanDTO emergencyDrillPlanDTO) {
        EmergencyDrillPlan emergencyDrillPlan = emergencyDrillPlanDTO.getEmergencyDrillPlan();
        List<EmergencyDivisionOfTasks> list = emergencyDrillPlanDTO.getEmergencyDivisionOfTasksList();
        int result = emergencyDrillPlanMapper.updateById(emergencyDrillPlan);
        if(result==0){
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }
        LambdaQueryWrapper<EmergencyDivisionOfTasks> queryWrapper=Wrappers.<EmergencyDivisionOfTasks>lambdaQuery();
        queryWrapper.eq(EmergencyDivisionOfTasks::getEmergencyDrillId,emergencyDrillPlan.getId());
        emergencyDivisionOfTasksMapper.delete(queryWrapper);
        list.forEach(detail -> {
            detail.setEmergencyDrillId(emergencyDrillPlan.getId());
            emergencyDivisionOfTasksMapper.insert(detail);
        });
        return true;

    }

    public IPage<EmergencyDrillPlanVO> getListByQO(EmergencyDrillPlanQO emergencyDrillPlanQO) {
        Page<EmergencyDrillPlanVO> page = new Page<>(emergencyDrillPlanQO.getCurrent(), emergencyDrillPlanQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<EmergencyDrillPlanVO> ans= emergencyDrillPlanMapper.getListByQO(page,emergencyDrillPlanQO);
        for (EmergencyDrillPlanVO record : ans.getRecords()) {
            Long id = record.getOrganizationId();
            Organization org = organizationMapper.selectById(record.getOrganizationId());
            record.setOrganizationName(org==null?"该部门不存在":org.getName());
            EmergencyPlanManagement plan=emergencyPlanManagementMapper.selectById(record.getNameRId());
            record.setNameEmerge(plan==null?"该应急预案不存在":plan.getName());

            QueryWrapper<EmergencyDivisionOfTasks> emergencyDivisionOfTasksQueryWrapper = new QueryWrapper<EmergencyDivisionOfTasks>();
            emergencyDivisionOfTasksQueryWrapper.eq("emergency_drill_id",record.getId());
            List<EmergencyDivisionOfTasks> emergencyDivisionOfTasksList=emergencyDivisionOfTasksMapper.selectList(emergencyDivisionOfTasksQueryWrapper);
            List<EmergencyDivisionOfTasksVO> voList=new LinkedList<>();
            List<String> participantNames=new LinkedList<>();
            for (int i = 0; i < emergencyDivisionOfTasksList.size(); i++) {
                EmergencyDivisionOfTasksVO vos=new EmergencyDivisionOfTasksVO();
                BeanUtils.copyProperties(emergencyDivisionOfTasksList.get(i),vos);
                SysUser userid =sysUserMapper.selectById(vos.getNameId());
                vos.setPersonnelName(userid==null?"该用户不存在":userid.getName());
                voList.add(vos);
                participantNames.add(userid==null?"该用户不存在":userid.getName());
            }
            record.setParticipantNames(participantNames.toString());
        }
        return ans;
    }
}




